package com.thorqq.wuxibusgui;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import com.google.gson.Gson;

public class Config
{
    static private final String CONFIG_FILE_NAME_TEST = ".test";

    private String mFileName = null;
    private Gson mJson = new Gson();

    public <T> T read(String filename, Class<T> classOfT)
    {
        mFileName = getConfigFileName(filename);
        
        try
        {

            File file = new File(mFileName);
            if (!file.exists())
            {
                write(classOfT.newInstance());

                Log.w("Open "
                        + mFileName
                        + " failed, create a new one, please modify it and restart this programme.");
            }

            InputStreamReader isr = new InputStreamReader(new FileInputStream(mFileName), "UTF-8");  
            BufferedReader reader = new BufferedReader(isr);  

            T obj = mJson.fromJson(reader, classOfT);
            reader.close();
            
            return obj;

        } 
        catch (Exception e)
        {
            e.printStackTrace();
            Log.ex(e);
            return null;
        }
    }

    public <T> boolean write(T obj)
    {

        try
        {
            File file = new File(mFileName);
            if (!file.getParentFile().exists()) 
            {  
                file.getParentFile().mkdirs();  
            } 
            
            String json = formatJson(mJson.toJson(obj));

            FileOutputStream writerStream = new FileOutputStream(file, false);  
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8")); 
            writer.write(json.toString());
            writer.close();

        } 
        catch (Exception e)
        {
            e.printStackTrace();
            Log.ex(e);
            return false;
        }

        return true;
    }
    
    private String getConfigFileName(String filename)
    {
        File testFile = new File(filename + CONFIG_FILE_NAME_TEST);
        if(!testFile.exists())
        {
            return filename;
        }
        else
        {
            return filename + CONFIG_FILE_NAME_TEST;
        }
    }

    private String formatJson(String jsonStr)
    {
        int level = 0;
        StringBuffer jsonForMatStr = new StringBuffer();
        for (int i = 0; i < jsonStr.length(); i++)
        {
            char c = jsonStr.charAt(i);
            if (level > 0
                    && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1))
            {
                jsonForMatStr.append(getLevelStr(level));
            }
            switch (c)
            {
            case '{':
            case '[':
                jsonForMatStr.append(c + "\n");
                level++;
                break;
            case ',':
                jsonForMatStr.append(c + "\n");
                break;
            case '}':
            case ']':
                jsonForMatStr.append("\n");
                level--;
                jsonForMatStr.append(getLevelStr(level));
                jsonForMatStr.append(c);
                break;
            default:
                jsonForMatStr.append(c);
                break;
            }
        }

        return jsonForMatStr.toString();

    }

    private String getLevelStr(int level)
    {
        StringBuffer levelStr = new StringBuffer();
        for (int levelI = 0; levelI < level; levelI++)
        {
            levelStr.append("\t");
        }
        return levelStr.toString();
    }
}